import { inject, injectable } from 'inversify';
import { RoleListModel } from '../models/role.list.model.ts';
import { UsersRolesRepository } from '../data/users.roles.repository.ts';

@injectable()
export class DeleteRoleUseCase {
  constructor(
    @inject(RoleListModel) private roleListModel: RoleListModel,
    @inject(UsersRolesRepository) private rolesRepository: UsersRolesRepository,
  ) {}

  async execute(_id: string) {
    const roleToRemove = this.roleListModel.roles.find(
      (role) => role._id === _id,
    );
    if (roleToRemove) {
      try {
        this.roleListModel.removeRole(_id);
        await this.rolesRepository.deleteRole(_id);
      } catch (e) {
        this.roleListModel.addRole(roleToRemove);
      }
    }
  }
}
